package com.hfxt.util;

import com.hfxt.entity.User;
import com.hfxt.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    //授权处理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        simpleAuthorizationInfo.addRole(user.getUserRoleName());
        return simpleAuthorizationInfo;
    }

    //认证处理
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        User user = userService.userLogin(userName);
        if (user == null) {
            throw new UnknownAccountException();
        } else {
            //shiro加密
            String salt = user.getSalt();
            ByteSource bytes = ByteSource.Util.bytes(salt);
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getUserPassword(), bytes, this.getName());
        }
        return simpleAuthenticationInfo;
    }
}
